<template>
  <div class="process-main">
    <div class="topBox add_btn_top">
      <el-button type="primary" size="mini" @click="handAdd"
        ><i class="el-icon-plus"></i>添加
      </el-button>
      <el-button class="button" size="mini" @click="handleImportDialog">
        <svg-icon class="svg-icon" icon-class="import" />导入
      </el-button>
      <el-button class="button" size="mini" @click="handleExport">
        <svg-icon class="svg-icon" icon-class="import" />导出
      </el-button>
      <div
        class="switch-text"
        :style="{ color: switchTextColor, marginLeft: '10px' }"
      >
        {{ switchText }}
      </div>
      <el-switch
        class="screenSwitch"
        active-color="#2680D2"
        @change="openScrenn"
        v-model="screen"
      >
      </el-switch>
    </div>
    <div class="boxLayout">
      <div
        :style="{
          width: screen ? '75%' : '100%',
          background: '#fff'
        }"
      >
        <el-table
          :span-method="objectSpanMethod"
          size="small"
          border
          v-loading="loading"
          ref="topicTable"
          class="cell_padding_0"
          :tree-props="{ children: 'children' }"
          row-key="id"
          default-expand-all
          :data="tableData"
          height="100px"
          v-adaptive
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="50" align="center">
          </el-table-column>
          <el-table-column
            prop="partNumber"
            label="零件号"
            align="center"
            sortable
            min-width="130"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="partName"
            min-width="130"
            label="零件名称"
            :show-overflow-tooltip="true"
          >
            <!-- <template slot-scope="scope">
              <span v-if="scope.row.type != 2">
                {{ scope.row.technology ? scope.row.technology.partName : "" }}
              </span>
          
            </template> -->
          </el-table-column>
          <el-table-column
            align="center"
            prop="version"
            min-width="130"
            label="工艺版次"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="entrustProcessNumber"
            min-width="130"
            label="委托工序号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="entrustProcessName"
            min-width="130"
            label="委托工序名称"
          ></el-table-column>
          <el-table-column
            min-width="130"
            prop="processNumber"
            label="工序/工步号"
            align="center"
          >
            <template slot-scope="scope">
              <span
                @click="handleIconToggle(scope.row.token)"
                style="cursor: pointer; color: #409eff"
              >
                {{ scope.row.processNumber }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            min-width="130"
            align="center"
            prop="processName"
            :show-overflow-tooltip="true"
            label="工序/工步名称"
          >
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="stepNumber"
            :show-overflow-tooltip="true"
            label="工步号"
          >
            <template slot-scope="scope">
              <span
                @click="handleIconToggle(scope.row.token, scope.row.stepNumber)"
                style="cursor: pointer; color: #409eff"
              >
                {{ scope.row.stepNumber }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="stepName"
            :show-overflow-tooltip="true"
            label="工步名称"
          >
          </el-table-column> -->
          <el-table-column
            align="center"
            v-if="isTabShow('模板')"
            prop="version"
            label="模板"
            min-width="130"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row &&
                  scope.row.technologyTemplate &&
                  scope.row.technologyTemplate.name
              }}
            </template>
          </el-table-column>

          <!-- <el-table-column
            prop="deviceTypeName"
            label="设备类型"
            width="120"
            :show-overflow-tooltip="true"
            v-if="isTabShow('设备类型')"
          >
            <template slot-scope="scope">
              {{ scope.row.deviceTypeName }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="isTabShow('设备编号')"
            prop="deviceList"
            label="设备编号"
            width="120"
            :show-overflow-tooltip="true"
          >
          </el-table-column> -->
          <el-table-column
            align="center"
            v-if="isTabShow('工序版次')"
            prop="processVersion"
            min-width="130"
            label="工序版次"
          ></el-table-column>
          <el-table-column
            align="center"
            v-if="isTabShow('材料牌号')"
            prop="materialMark"
            min-width="130"
            label="材料牌号"
          ></el-table-column>

          <el-table-column
            align="center"
            prop="state"
            label="状态"
            min-width="130"
            v-if="isTabShow('状态')"
          >
            <template slot-scope="scope">
              <span
                :style="
                  scope.row.state == 'false'
                    ? 'color: #F56C6C;'
                    : 'color: #67C23A'
                "
              >
                {{ formatState(scope.row.state) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="createdDate"
            label="创建时间"
            min-width="160"
            v-if="isTabShow('创建时间')"
          >
            <template slot-scope="scope">
              {{ scope.row.createdDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="endDate"
            label="有效期"
            align="center"
            min-width="160"
            v-if="isTabShow('有效期')"
          >
            <template slot-scope="scope">
              {{ scope.row.endDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            min-width="130"
            prop="author"
            :show-overflow-tooltip="true"
            label="创建人"
            v-if="isTabShow('创建人')"
          ></el-table-column>
          <el-table-column
            label="操作"
            min-width="130"
            fixed="right"
            align="center"
          >
            <!-- eslint-disable-next-line -->
            <template slot="header" slot-scope="scope">
              <div class="flex-x flex-space" style="padding: 0 10px">
                <div>操作</div>
                <el-popover width="100" trigger="click">
                  <div class="column_search_box">
                    <div class="column_title">自定义表头字段</div>
                    <el-checkbox-group v-model="colCheckList">
                      <div class="flex-y column_search">
                        <el-checkbox
                          :label="item.label"
                          v-for="item in getColumnList"
                          :key="item.label"
                        >
                          {{ item.label }}</el-checkbox
                        >
                      </div>
                    </el-checkbox-group>
                  </div>
                  <span slot="reference" class="el-icon-s-grid"></span>
                </el-popover>
              </div>
            </template>
            <template slot-scope="scope" v-if="scope.row.token">
              <div class="table_btns flex-x flex-space" style="padding: 0 10px">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit-outline"
                  @click="handEdit(scope.row, scope.$index)"
                ></el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handDelete(scope.row.token, scope.$index)"
                ></el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-view"
                  @click="handNavTo(scope.row.token)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <Pagination
          @pagination="pagination"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          :pageSizes.sync="pageSizes"
        />
      </div>
      <SearchFilter
        :tableData="allData"
        :templateList="templateList"
        v-show="screen"
        @setFilterList="setFilterList"
        :userList="userList"
      ></SearchFilter>
    </div>
    <AddDialog
      :isTechnoNavto="isTechnoNavto"
      :templateList="templateList"
      :key="generateId"
      :token="token"
      :showDialog.sync="showDialog"
      :isedit="isedit"
      :title="title"
      @closeDialog="closeDialog"
      ref="addDialogRef"
    ></AddDialog>

    <ExportDialog
      :showDialog.sync="showExportDialog"
      :tableData="allData"
      :templateList="templateList"
      :userList="userList"
    ></ExportDialog>
    <ImportDialog
      @closeDialog="closeDialog"
      :templateList="templateList"
      :showDialog.sync="showImportDialog"
    ></ImportDialog>
  </div>
</template>

<script>
const COLUMN_LIST = [
  {
    label: "工艺版次"
  },
  {
    label: "模板"
  },

  // {
  //   label: "设备类型",
  // },
  // {
  //   label: "设备编号",
  // },
  {
    label: "工序版次"
  },
  {
    label: "材料牌号"
  },

  {
    label: "状态"
  },
  {
    label: "创建时间"
  },
  {
    label: "有效期"
  },
  {
    label: "创建人"
  }
];
import ImportDialog from "./ImportDialog.vue";
import Pagination from "@/views/common/page";
import SearchFilter from "./searchFilter.vue";
import AddDialog from "./AddDialog.vue";
import { generateId } from "@/utils/index";
import { uniqueTree, setDevInfolist } from "./js/index";
import { paginationMixins } from "@/mixin/pagination";
import { getUserList } from "@/api/userAuth";
import ExportDialog from "./ExportDialog.vue";
import {
  delTechnology,
  getTemplate,
  getTemplateList,
  getTechnology,
  getTechnologyToken
} from "@/api/technology";
import _ from "lodash";
export default {
  mixins: [paginationMixins],
  components: {
    Pagination,
    SearchFilter,
    AddDialog,
    ExportDialog,
    ImportDialog
  },

  data() {
    return {
      pos: 0,
      pos2: 0,
      pos3: 0,
      spanData: [],
      spanData2: [],
      spanData3: [],
      showImportDialog: false,
      showExportDialog: false,
      colCheckList: COLUMN_LIST.map(item => item.label),
      loading: false,
      total: 0,
      isTechnoNavto: false,
      title: "主工艺",
      screen: false,
      screenShow: false,
      switchTextColor: "#666666",
      switchText: "显示筛选",
      filterData: "",
      showDialog: false,
      isedit: false,
      editmetaData: {},
      editmetaData: true,
      token: "",
      tableData: [],
      templateList: [],
      form: {
        author: "", //当前用户
        state: "", //状态
        name: "", //名称
        templateId: "", //模板id
        url: "" //模板的url
      },
      userList: [],
      allData: []
    };
  },
  computed: {
    isTabShow() {
      return function(name) {
        return this.colCheckList.includes(name);
      };
    },
    getColumnList() {
      // console.log("this.tableData :>> ", this.tableData);
      return COLUMN_LIST;
      // if (this.tableData.length) {
      //   return COLUMN_LIST.concat(this.otherCol);
      // } else {
      //   return COLUMN_LIST;
      // }
    },
    generateId() {
      return generateId();
    }
  },
  async mounted() {
    getTechnology({
      page: 1,
      pageSize: 0
    })
      .then(r => {
        let { results, numResults } = r.data;
        this.allData = results;
      })
      .finally(f => {
        this.loading = false;
      });
    getUserList().then(res => {
      const { data } = res.data;
      this.userList = data;
    });

    await this.getTemplateList();
    let technologyFrom = this.$route.params.technologyFrom;
    if (technologyFrom) {
      technologyFrom = JSON.parse(technologyFrom);
      console.log("technologyFrom :>> ", technologyFrom);
      technologyFrom.technologyId = technologyFrom.id;
      technologyFrom.state = "true";
      delete technologyFrom.id;
      const {
        templateId,
        partNumber,
        processNumber,
        technologyId
      } = technologyFrom;

      this.$nextTick(() => {
        this.showDialog = true;
        this.isTechnoNavto = true;
        this.$refs.addDialogRef.form = {
          ...this.$refs.addDialogRef.form,
          ...technologyFrom
        };
        // 获取主工艺
        this.$refs.addDialogRef.templateChange(templateId);
        this.$refs.addDialogRef.getProcessList(partNumber, processNumber);
      });
    }

    this.init();
  },
  // technologyParameter
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // if (columnIndex === 4) {
      //   const _row = this.spanData2[rowIndex];
      //   const _col = _row > 0 ? 1 : 0;
      //   return {
      //     rowspan: _row,
      //     colspan: _col,
      //   };
      // }
      if ([1, 2, 3, 4, 5].includes(columnIndex)) {
        const _row = this.spanData[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.init();
    },
    handleImportDialog() {
      this.showImportDialog = true;
    },
    handleExport() {
      this.showExportDialog = true;
    },
    handleIconToggle(token, processNumber) {
      this.$router.push({
        name: "recipeDetails",
        query: {
          token
          // processNumber,
        }
      });
    },
    handNavTo(token) {
      this.$router.push({
        name: "recipeExhibition",
        query: {
          token,
          type: 2
        }
      });
    },
    //获取模板列表
    getTemplateList() {
      return new Promise((resolve, reject) => {
        var params = {
          page: 1,
          pageSize: 0
        };
        getTemplate(params).then(res => {
          const { results } = res.data;
          this.templateList = results;
          resolve();
        });
      });
    },

    formatState(data) {
      if (data == "true") {
        return "可用";
      } else if (data == "false") {
        return "禁用";
      }
    },
    //筛选调用
    setFilterList(data) {
      if (data) {
        this.switchTextColor = "#2680D2";
        this.switchText = "显示筛选 ( 已筛选 )";
      } else {
        this.switchTextColor = "#666666";
        this.switchText = "显示筛选";
      }
      this.filterData = data;
      this.init();
    },
    init() {
      this.loading = true;
      this.params = {
        page: this.pageNum,
        pageSize: this.pageSize,
        includeTemplate: true
        // includeTechnology: true,
      };
      if (this.filterData) {
        this.params = {
          ...this.params,
          ...this.filterData
          // includeTechnology: true,
        };
      }
      this.tableData = [];
      getTechnology(this.params)
        .then(r => {
          let { results, numResults } = r.data;
          this.total = numResults;
          // results = _.sortBy(results, [
          //   "updatedDate",
          //   "partNumber",
          //   "partName",
          //   "version",
          // ]);
          this.tableData = results;
          this.getSpanData(this.tableData);
          // results = _.sortBy(results, [
          //   "partNumber",
          //   "partName",
          //   "version",
          //   "updatedDate",
          // ]);
        })
        .finally(f => {
          this.loading = false;
        });
    },
    getSpanData(data) {
      // 存放计算好的合并单元格的规则
      this.spanData = [];
      this.spanData2 = [];
      // this.spanData3 = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanData.push(1);
          this.pos = 0;
          this.spanData2.push(1);
          this.pos2 = 0;
          // this.spanData3.push(1);
          // this.pos3 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          const ispartNumber = data[i].partNumber === data[i - 1].partNumber;
          const ispartName = data[i].partName === data[i - 1].partName;
          const isversion = data[i].version === data[i - 1].version;
          const isentrustProcessName =
            data[i].entrustProcessName === data[i - 1].entrustProcessName;
          const ispProcessNumber =
            data[i].entrustProcessNumber === data[i - 1].entrustProcessNumber;
          if (
            ispartNumber &&
            ispartName &&
            isversion &&
            ispProcessNumber &&
            isentrustProcessName
          ) {
            this.spanData[this.pos] += 1;
            this.spanData.push(0);
          } else {
            this.spanData.push(1);
            this.pos = i;
          }
          if (ispProcessNumber) {
            this.spanData2[this.pos2] += 1;
            this.spanData2.push(0);
          } else {
            this.spanData2.push(1);
            this.pos2 = i;
          }
          if (isversion) {
            this.spanData3[this.pos3] += 1;
            this.spanData3.push(0);
          } else {
            this.spanData3.push(1);
            this.pos3 = i;
          }
        }
      }
    },
    indexMethod(index) {
      return index + 1;
    },
    // 显示筛选窗
    openScrenn() {},
    //添加
    handAdd() {
      this.showDialog = true;
      this.isTechnoNavto = false;
    },
    //编辑
    handEdit(row) {
      this.showDialog = true;
      // this.token = token;
      // 拼接配方的token
      this.token = row.token + "_" + row.processVersion;
      this.isedit = true;
    },
    //删除
    handDelete(token) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delTechnology(token).then(res => {
            this.$msg({
              type: "success",
              message: "删除成功!"
            });
            this.init();
          });
        })
        .catch(c => {});
    },
    closeDialog(isRefresh) {
      console.log("isRefresh :>> ", isRefresh);
      // isRefresh是否刷新
      if (isRefresh === true) {
        this.init();
      }
      this.showDialog = false;
      this.isedit = false;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/processCss/baseStyle.css";

.table_btns {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  height: 100%;
}
.cell_padding_0 {
  .device_box {
    display: flex;
    align-items: center;
    /* text-align: center; */
    .device_line_box {
      width: 10px;
      min-width: 10px;
      /* margin-right: 4px; */
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .device_line {
      /* height: 38px; */
      width: 1px;
      border-left: 1px dashed #009cff;
    }
  }
  /deep/ .el-table__expand-icon {
    display: none !important;
  }
  /deep/ .has-gutter {
    .cell {
      /* padding: 0; */
    }
    /* tr th:nth-child(1) {
      .cell {
        padding: 0 10px;
      }
    } */
  }
  /deep/ .el-table__row {
    /* td {
      padding: 0;
    } */
    .type_line {
      display: flex;
      align-items: center;
      /* padding-left: 20px; */
      height: 48px;
      .type_line-1 {
        margin-left: 20px;
        height: 48px;
        /* width: 1px; */
        border-left: 1px dashed #ffa0de;
        /* background-color: #ffa0de; */
      }
      .type_line-last {
        margin-left: 20px;
        height: 24px;
        width: 1px;
        /* background-color: #ffa0de; */
        border-left: 1px dashed #ffa0de;
        align-self: flex-start;
      }
      .type_line-2 {
        height: 1px;
        width: 90px;
        /* background-color: #ffa0de; */
        border-top: 1px dashed #ffa0de;
      }
    }

    /* .cell {
      height: 48px;
      padding: 0;
      line-height: 48px;
    }
    td:nth-child(3),
    td:nth-child(2) {
      .cell {
        padding: 0 !important;
      }
    }
    td:nth-child(1) {
      .cell {
        padding: 0 10px;
      }
    } */
    /* .el-table__indent,
    .el-table__placeholder {
      display: none;
    } */
  }
  /* /deep/ tbody .cell {
    padding: 0 !important;
  } */
}
.row_name {
  color: #409eff;
  cursor: pointer;
}
</style>
